//
//  ZZTextField.swift
//  swiftFrame
//
//  Created by hfzhangzhang on 2018/3/22.
//  Copyright © 2018年 hfzhangzhang. All rights reserved.
//

import UIKit

class ZZTextField: UITextField {

}
private var key: String?

extension UITextField{
    
    var maxLength: Int? {
        get {
            return (objc_getAssociatedObject(self, &key) as? Int)
        }
        set(newValue) {
            objc_setAssociatedObject(self, &key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
            if let value = newValue, value > 0 {
                self .addTarget(self, action: #selector(textFieldTextDidChangeForMaxLength), for: .editingChanged)
            }
        }
    }
    @objc func textFieldTextDidChangeForMaxLength() -> () {
        if let _ = self.text, let positionRange = self.markedTextRange  {
            guard self.position(from: positionRange.start, offset: 0) == nil else{
                return;
            }
        }
        if let max = self.maxLength, let text = self.text, text.count > 0,text.count > max{
            let index = text.index(text.startIndex, offsetBy: max)
            let sub = text[..<index]
            self.text = String(sub)
        }
        
    }
}
